﻿using System;
using System.IO;
using System.Reflection;
using System.Web.Hosting;

namespace Midas
{
    public class _cache
    {
        /// <summary>
        /// folder to store the data
        /// </summary>
        public static string cacheFolderName = string.Empty;
        public static int cacheExpireDays = 1;

        static _cache()
        {
            cacheFolderName = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "cache");
        }

        /// <summary>
        /// writes an object to a file.
        /// Overites existing files
        /// </summary>
        /// <param name="obj">the object to save</param>
        /// <param name="name">the name of the file</param>
        public static void SaveDataToCache(object obj, string name)
        {
            try
            {
                string path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), cacheFolderName);
                Directory.CreateDirectory(path);
                path = Path.Combine(path, name);
                File.WriteAllBytes(path, _tools.ObjectToBytes(obj));
            }
            catch
            {
            }
        }

        /// <summary>
        /// reads an object from a file.
        /// </summary>
        /// <param name="name">the name of the file</param>
        /// <returns>the object in the file,
        /// null if there is no file, expired or failed</returns>
        public static T LoadDataFromCache<T>(string name)
        {
            try
            {
                string path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), cacheFolderName, name);
                if ((DateTime.Now - File.GetLastWriteTime(path)).TotalDays < cacheExpireDays)
                {
                    return (T)_tools.BytesToObject(File.ReadAllBytes(path));
                }
            }
            catch
            {
            }
            return default(T);
        }
    }
}